package database

import (
	"database/sql"
	"errors"
	"time"

	"gitee.com/chenjihao00/standard-repo/basic/configrations"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func ConnectToDBFromMysqlConfig(cfg *configrations.MysqlConfig) (*gorm.DB, error) {
	var db *gorm.DB
	var err error
	var sqlDB *sql.DB
	if db, err = gorm.Open(mysql.Open(cfg.Datasource.ToDNS()), &gorm.Config{}); err != nil {
		return nil, errors.New("[ConnectToDBFromMysqlConfig] connect to db failed")
	}
	if sqlDB, err = db.DB(); err != nil {
		return nil, errors.New("[ConnectToDBFromMysqlConfig] connect to db failed")
	}
	sqlDB.SetMaxIdleConns(cfg.Datasource.MaxIdleConns)
	sqlDB.SetMaxOpenConns(cfg.Datasource.MaxOpenConns)
	sqlDB.SetConnMaxLifetime(time.Duration(cfg.Datasource.ConnMaxLifetime) * time.Second)
	sqlDB.SetConnMaxIdleTime(time.Duration(cfg.Datasource.ConnMaxIdleTime) * time.Second)
	return db, nil
}
